package com.bullsora.kindlerss.business.mail;

import com.google.appengine.api.mail.MailService;
import com.google.appengine.api.mail.MailServiceFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author sorin.buliarca@iquesint.com
 */
public class KindleMailSender {

  public static final Log LOG = LogFactory.getLog(KindleMailSender.class);

  private static final String KINDLE_ACCOUNT_SUFFIX = "@free.kindle.com";

  private String from;

  public void sendMessage(String htmlToSend, String fileName, String kindleAccount) {
    LOG.info(String.format("Sending mail with attachment: [%1$s]: %2$s", fileName, htmlToSend));

    try {
      MailService mailService = MailServiceFactory.getMailService();

      MailService.Message msg = new MailService.Message();
      msg.setSender(from);
      msg.setTo(kindleAccount + KINDLE_ACCOUNT_SUFFIX);
      msg.setSubject("feed");
      msg.setTextBody("feed");
      MailService.Attachment attachment = new MailService.Attachment(fileName, htmlToSend.getBytes());
      msg.setAttachments(attachment);
      mailService.send(msg);
    } catch (Exception e) {
      LOG.error("Error while sending mail", e);
      throw new MailException(e);
    }
  }


  public String getFrom() {
    return from;
  }

  public void setFrom(String from) {
    this.from = from;
  }

}
